package logic

import (
	"com-man-sys/comrpc/comrpc"
	"com-man-sys/comrpc/internal/svc"
	"com-man-sys/models/cache"
	"com-man-sys/models/mysql"
	"com-man-sys/pkg"
	"context"
	"errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *comrpc.LoginRequest) (*comrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(cache.Ctx, "captcha"+in.Mobile).Result()
	if result != in.CaptchaName {
		return nil, errors.New("图形验证码错误，请重新输入")
	}
	s, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if s != in.SendSmsName {
		return nil, errors.New("短信验证码错误，请重新输入")
	}
	user := &mysql.User{
		Mobile:   in.Mobile,
		Password: pkg.Md5(in.Password),
	}
	if len(in.Password) < 8 {
		return nil, errors.New("密码长度不对")
	}

	err := user.LoginFind(mysql.DB, in.Mobile)
	if err != nil {
		return nil, err
	}
	if pkg.Md5(in.Password) != user.Password {
		return nil, errors.New("密码错误")
	}
	cache.Rdb.Del(cache.Ctx, "captcha"+in.Mobile)

	cache.Rdb.Del(cache.Ctx, "sendSms"+in.Mobile)
	return &comrpc.LoginResponse{
		Mobile: user.Mobile,
	}, nil
}
